<template>
  <div class="add">
    <Doctor :doctor="doctor" @add="add" :disabled="disabled"/>
  </div>
</template>

<script>
// @ is an alias to /src
import Doctor from '@/components/Doctor';
import { validate } from '@/util/index';

export default {
  name: 'addDoctor',

  components: {
    Doctor
  },

  data() {
    return {
      doctor: {},
      disabled: false
    }
  },

  methods: {
    add(doctor) {
      const fields = ['dc_name', 'dc_pic', 'working_week', 'start_hour', 'end_hour', 'dc_intro', 'dc_skill'];
      const isValidated = validate(this.$weui.form, this.doctor, fields);

      if (this.disabled || !isValidated) {
        return false;
      }

      this.disabled = true;
      this.$axios
        .post('http://api.qy-clinic.com/doctor', doctor)
        .then(({ data }) => {
          this.disabled = false;
          if (!data.dc_id) {
            throw new Error(data.name);
          }
          this.$weui.toast('添加成功', 1500);
          this.$router.push({ name: 'home' });
        })
        .catch(err => {
          this.disabled = false;
          this.$weui.alert(err.message);
        });
    }
  }
}
</script>
